모든 데이터 분석 모형은 숫자로 구성된 고정 차원 벡터를 독립 변수로 하고 있으므로 문서(document)를 분석을 하는 경우에도 숫자로 구성된 특징 벡터(feature vector)를 문서로부터 추출하는 과정이 필요하다. 이러한 과정을 문서 전처리(document preprocessing)라고 한다.
문서를 숫자 벡터로 변환하는 가장 기본적인 방법은 BOW (Bag of Words) 이다. BOW 방법에서는 전체 문서 $\{D_1, D_2, \ldots, D_n\}$ 들를 구성하는 고정된 단어장(vocabulary) $\{W_1, W_2, \ldots, W_m\}$ 를 만들고 $D_i$라는 개별 문서에 단어장에 해당하는 단어들이 포함되어 있는지를 표시하는 방법이다.
$$ \text{ if word $W_j$ in document $D_i$ }, \;\; \rightarrow x_{ij} = 1 $$Scikit-Learn 의 feature_extraction.text 서브 패키지는 다음과 같은 문서 전처리용 클래스를 제공한다.
CountVectorizer: TfidfVectorizer: HashingVectorizer:
In [2]:
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?',
'The last document?',
]
vect = CountVectorizer()
vect.fit(corpus)
vect.vocabulary_
Out[2]:
In [3]:
vect.transform(['This is the second document.']).toarray()
Out[3]:
In [4]:
vect.transform(['Something completely new.']).toarray()
Out[4]:
In [5]:
vect.transform(corpus).toarray()
Out[5]:
CountVectorizer는 다양한 인수를 가진다. 그 중 중요한 것들은 다음과 같다.
stop_words : 문자열 {‘english’}, 리스트 또는 None (디폴트)analyzer : 문자열 {‘word’, ‘char’, ‘char_wb’} 또는 함수tokenizer : 함수 또는 None (디폴트)token_pattern : stringngram_range : (min_n, max_n) 튜플max_df : 정수 또는 [0.0, 1.0] 사이의 실수. 디폴트 1min_df : 정수 또는 [0.0, 1.0] 사이의 실수. 디폴트 1vocabulary : 사전이나 리스트Stop Words 는 문서에서 단어장을 생성할 때 무시할 수 있는 단어를 말한다. 보통 영어의 관사나 접속사, 한국어의 조사 등이 여기에 해당한다. stop_words 인수로 조절할 수 있다.
In [6]:
vect = CountVectorizer(stop_words=["and", "is", "the", "this"]).fit(corpus)
vect.vocabulary_
Out[6]:
In [7]:
vect = CountVectorizer(stop_words="english").fit(corpus)
vect.vocabulary_
Out[7]:
토큰은 문서에서 단어장을 생성할 때 하나의 단어가 되는 단위를 말한다. analyzer, tokenizer, token_pattern 등의 인수로 조절할 수 있다.
In [8]:
vect = CountVectorizer(analyzer="char").fit(corpus)
vect.vocabulary_
Out[8]:
In [9]:
import nltk
nltk.download("punkt")
vect = CountVectorizer(tokenizer=nltk.word_tokenize).fit(corpus)
vect.vocabulary_
Out[9]:
In [10]:
vect = CountVectorizer(token_pattern="t\w+").fit(corpus)
vect.vocabulary_
Out[10]:
n-그램은 단어장 생성에 사용할 토큰의 크기를 결정한다. 1-그램은 토큰 하나만 단어로 사용하며 2-그램은 두 개의 연결된 토큰을 하나의 단어로 사용한다.
In [11]:
vect = CountVectorizer(ngram_range=(2,2)).fit(corpus)
vect.vocabulary_
Out[11]:
In [12]:
vect = CountVectorizer(ngram_range=(1,2), token_pattern="t\w+").fit(corpus)
vect.vocabulary_
Out[12]:
max_df, min_df 인수를 사용하여 문서에서 토큰이 나타난 횟수를 기준으로 단어장을 구성할 수도 있다. 토큰의 빈도가 max_df로 지정한 값을 초과 하거나 min_df로 지정한 값보다 작은 경우에는 무시한다. 인수 값은 정수인 경우 횟수, 부동소수점인 경우 비중을 뜻한다.
In [13]:
vect = CountVectorizer(max_df=4, min_df=2).fit(corpus)
vect.vocabulary_, vect.stop_words_
Out[13]:
In [14]:
vect.transform(corpus).toarray().sum(axis=0)
Out[14]:
TF-IDF(Term Frequency – Inverse Document Frequency) 인코딩은 단어를 갯수 그대로 카운트하지 않고 모든 문서에 공통적으로 들어있는 단어의 경우 문서 구별 능력이 떨어진다고 보아 가중치를 축소하는 방법이다.
구제적으로는 문서 $d$(document)와 단어 $t$ 에 대해 다음과 같이 계산한다.
$$ \text{tf-idf}(d, t) = \text{tf}(d, t) \cdot \text{idf}(d, t) $$여기에서
$\text{idf}(d, t)$ : inverse document frequency
$$ \text{idf}(d, t) = \log \dfrac{n_d}{1 + \text{df}(t)} $$
$n_d$ : 전체 문서의 수
In [15]:
from sklearn.feature_extraction.text import TfidfVectorizer
In [16]:
tfidv = TfidfVectorizer().fit(corpus)
tfidv.transform(corpus).toarray()
Out[16]:
CountVectorizer는 모든 작업을 in-memory 상에서 수행하므로 데이터 양이 커지면 속도가 느려지거나 실행이 불가능해진다. 이 때
HashingVectorizer를 사용하면 Hashing Trick을 사용하여 메모리 및 실행 시간을 줄일 수 있다.
In [17]:
from sklearn.datasets import fetch_20newsgroups
twenty = fetch_20newsgroups()
len(twenty.data)
Out[17]:
In [18]:
%time CountVectorizer().fit(twenty.data).transform(twenty.data)
Out[18]:
In [19]:
from sklearn.feature_extraction.text import HashingVectorizer
hv = HashingVectorizer(n_features=10)
In [20]:
%time hv.transform(twenty.data)
Out[20]:
In [21]:
corpus = ["imaging", "image", "imagination", "imagine", "buys", "buying", "bought"]
vect = CountVectorizer().fit(corpus)
vect.vocabulary_
Out[21]:
In [22]:
from sklearn.datasets import fetch_20newsgroups
twenty = fetch_20newsgroups()
docs = twenty.data[:100]
In [23]:
vect = CountVectorizer(stop_words="english", token_pattern="wri\w+").fit(docs)
vect.vocabulary_
Out[23]:
In [27]:
from nltk.stem import SnowballStemmer
class StemTokenizer(object):
def __init__(self):
self.s = SnowballStemmer('english')
self.t = CountVectorizer(stop_words="english", token_pattern="wri\w+").build_tokenizer()
def __call__(self, doc):
return [self.s.stem(t) for t in self.t(doc)]
vect = CountVectorizer(tokenizer=StemTokenizer()).fit(docs)
vect.vocabulary_
Out[27]:
In [31]:
import urllib2
import json
import string
from konlpy.utils import pprint
from konlpy.tag import Hannanum
hannanum = Hannanum()
req = urllib2.Request("https://www.datascienceschool.net/download-notebook/708e711429a646818b9dcbb581e0c10a/")
opener = urllib2.build_opener()
f = opener.open(req)
json = json.loads(f.read())
cell = ["\n".join(c["source"]) for c in json["cells"] if c["cell_type"] == u"markdown"]
docs = [w for w in hannanum.nouns(" ".join(cell)) if ((not w[0].isnumeric()) and (w[0] not in string.punctuation))]
In [37]:
vect = CountVectorizer().fit(docs)
count = vect.transform(docs).toarray().sum(axis=0)
plt.bar(range(len(count)), count)
plt.show()
In [38]:
pprint(zip(vect.get_feature_names(), count))